package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("LawService")
@Transactional

public class LawServiceImpl extends CmiEmaService implements LawService {
	public LawServiceImpl() {
	}

	@Transactional
	public Law saveLaw(Law law) {
		Set<Event> existingEventsForEvent = new HashSet<Event>();

		Set<Event> selectedEventsForEvent = law.getEventsForLaw();

		if (law.getId() == null) {

			Law existingLaw = lawDAO.findLawByPhysicalPrimaryKey(law.getName());

			if (isEquals(law, existingLaw)) {
				return existingLaw;
			}

			law = lawDAO.store(law);
			lawDAO.flush();

			for (Event relatedEvent : selectedEventsForEvent) {
				relatedEvent.getLawsForEvent().add(law);
				eventDAO.store(relatedEvent);
			}
		} else {
			Law existingLaw = lawDAO.findLawByPrimaryKey(law.getId());

			existingEventsForEvent = existingLaw.getEventsForLaw();

			Set<Event> prepareDeleteEventsForEvent = new HashSet<Event>();
			Set<Event> prepareAddEventsForEvent = new HashSet<Event>();

			prepareDeleteEventsForEvent.addAll(selectedEventsForEvent);
			prepareDeleteEventsForEvent.addAll(existingEventsForEvent);

			prepareAddEventsForEvent.addAll(selectedEventsForEvent);
			prepareAddEventsForEvent.addAll(existingEventsForEvent);

			prepareDeleteEventsForEvent.removeAll(selectedEventsForEvent);
			prepareAddEventsForEvent.removeAll(existingEventsForEvent);

			for (Event relatedEvent : prepareAddEventsForEvent) {

				relatedEvent.getLawsForEvent().add(existingLaw);
				eventDAO.store(relatedEvent);
			}

			for (Event relatedEvent : prepareDeleteEventsForEvent) {

				relatedEvent.getLawsForEvent().remove(existingLaw);
				eventDAO.store(relatedEvent);
			}
			law = lawDAO.store(law);
			lawDAO.flush();
		}

		eventDAO.flush();
		return law;
	}

	public void deleteLaw(Law law) {
		lawDAO.remove(law);
		lawDAO.flush();
	}

	@Transactional
	public void deleteLaws(Set<Integer> deleteLawsId) {
		Query query = lawDAO.createNamedQuery("deleteLawsById", -1, -1);
		query.setParameter(1, deleteLawsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Law> loadLaws() {
		return lawDAO.findAllLaws();

	}

	@Transactional
	public Set<Law> loadReferenceLaws(Set<Law> laws) {
		Iterator<Law> lawsIterator = laws.iterator();
		Set<Law> referencedLaws = new HashSet<>();
		while (lawsIterator.hasNext()) {
			Law currentLaw = lawsIterator.next();

			if (!currentLaw.getEventsForLaw().isEmpty()) {
				referencedLaws.add(currentLaw);
				continue;
			}
		}
		return referencedLaws;
	}

	public Set<Law> loadLawsByIdSet(Set<Integer> lawIdSet) {

		Iterator<Integer> lawIdIterator = lawIdSet.iterator();
		Set<Law> lawSet = new HashSet<>();
		while (lawIdIterator.hasNext()) {
			Integer id = lawIdIterator.next();
			Law currentLaw = lawDAO.findLawById(id);
			lawSet.add(currentLaw);
		}
		return lawSet;
	}

	@Transactional
	public List<Law> findAllLaws(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Law>(lawDAO.findAllLaws(startResult, maxRows));
	}

	@Transactional
	public Law findLawByPrimaryKey(Integer id) {
		return lawDAO.findLawByPrimaryKey(id);
	}

	@Transactional
	public Integer countLaws() {
		return ((Long) lawDAO.createQuerySingleResult("select count(o) from Law o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countLaws(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Law.class);
		return ((Long) lawDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countLawsByName(String queryName) {
		Query query = lawDAO.createNamedQuery("countLawsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countLawsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Law.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadLawObjectReferencedSet(Law law) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventsIds = new HashSet<Integer>();
		for (Event event : law.getEventsForLaw()) {
			eventsIds.add(event.getId());
		}
		objectReferencedSetMap.put("eventsIds", eventsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadLawClassReferencedSet(Law law) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());

		return classReferencedSetMap;
	}

	public boolean isEquals(Law law, Object obj) {
		if (obj == law)
			return true;
		if (!(obj instanceof Law))
			return false;
		Law comparedLaw = (Law) obj;
		if (!CheckPropertyEqual(law.getName(), comparedLaw.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

